package com.kaili.basic.controller;

import com.kaili.basic.service.IBaseCompanyService;
import com.kaili.basic.version.ApiVersion;
import com.kaili.common.util.SnowflakeIdFactory;
import com.kaili.common.util.VerifyUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.Base64Utils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.math.BigInteger;
import java.util.HashMap;
import java.util.Map;
import java.util.Random;

/**
 * Created by renzhikun on 18-11-20.
 */
@RestController
@ApiVersion(1)
@RequestMapping("/{api_version}")
@Api(tags = "登录验证", description = "登录验证相关API")
public class BaseCodeController {

    @Autowired
    protected HttpServletRequest request;
    @Autowired
    protected HttpServletResponse response;
    @Autowired
    private IBaseCompanyService baseCompanyService;

    @ApiOperation("生成验证码")
    @GetMapping("/getCode")
    public Map getCode() throws Exception {
        Object[] objects = VerifyUtil.creatImage();
        BufferedImage image = (BufferedImage) objects[1];
        response.setContentType("image/png");
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        ImageIO.write(image, "png", out);
        String base = Base64Utils.encodeToString(out.toByteArray());
        String key = SnowflakeIdFactory.getNextId();
        baseCompanyService.saveVerifyCode(key, objects[0].toString());
        Map<String, String> map = new HashMap();
        map.put("image", base);
        map.put("key", key);
        return map;
    }

    @ApiOperation("获取原根和模值")
    @GetMapping("/getDH")
    public Map<String, Object> getDH() {
        BigInteger a = BigInteger.valueOf(2);
        BigInteger p = BigInteger.probablePrime(6, new Random());
        BigInteger x = BigInteger.probablePrime(6, new Random());
        String key = SnowflakeIdFactory.getNextId();
        baseCompanyService.saveVerifyCode(key, String.valueOf(x));
        BigInteger y = a.modPow(x, p);
        Map<String, Object> map = new HashMap<>();
        map.put("a", a);
        map.put("p", p);
        map.put("y", y);
        map.put("key", key);
        return map;
    }

}
